<?php

// +----------------------------------------------------------------------
// | ZAJJ Software [ 我宁可 为做过的事而后悔，也不想 因为没尝试而后悔。 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 扬州择安家居有限公司 All rights reserved.
// +----------------------------------------------------------------------
// | Author: James <376785986@qq.com> <http://www.baidu.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Think\Model;

/**
 * 推送模板控制器
 * @author James
 * 2016-06-17
 */
class PushedController extends AdminController {

    /**
     * 推送模板管理
     * @author James
     * 2016-06-17
     */
    public function index() {

        $title = I('title');

        $map['title'] = array('like', '%' . (string) $title . '%');
        $map['status'] = 1;

        $list = $this->lists('Pushed', $map,'createAt desc');
        int_to_string($list);

        $this->assign('_list', $list);
        $this->meta_title = '推送模板列表';
        $this->display();
    }

    /**
     * 推送模板发布
     * @author James
     * 2016-06-17
     */
    public function add($title = "",$bin = "",$templet = "",$content = "",$jump_url = "") {
        if (IS_POST) {

            $pkeys_array = I('pkeys');
            $pvalues_array = I('pvalues');
            $pcolors_array = I('pcolors');

            //非空校验
            if (!$title) {
                $this->error("亲,模板标题不能为空哦!");
            }
            if (!$bin) {
                $this->error("亲,模板简码不能为空哦!");
            }
            if (!$templet) {
                $this->error("亲,公众号模板ID不能为空哦!");
            }
            if (!$content) {
                $this->error("亲,模板详情不能为空哦!");
            }

            if(count($pkeys_array) == 0){
                $this->error("亲.模板参数一行都没有,你想干嘛?");
            }

            for ($i = 0; $i < count($pkeys_array); $i++) {
                if ($pkeys_array[$i] == ""  || $pvalues_array[$i] == "" || $pcolors_array[$i] == "") {
                    $this->error("亲,请确保每一行模板参数都不能有空值哦.");
                }
            }

            //校验模板简码不能重复录入
            $map['bin'] = $bin;
            $map['status'] = 1;
            $list = M('Pushed')->where($map)->select();
            if(sizeof($list)>0){
                $this->error("模板简码不能重复录入");
            }

            //数据操作
            $PushedData = array('title'=>$title,'bin'=>$bin,'templet' => $templet,'content' => $content,'jump_url' => $jump_url,'createAt' => NOW_TIME,'updateAt' => NOW_TIME);
            $Pushed = D('Pushed');
            if ($Pushed->create($PushedData)) {
                if(!($pid = $Pushed->add())) {
                    $this->error("新模板添加失败！");
                }

                for ($i = 0; $i < count($pkeys_array); $i++) {
                    $dataList[] = array(
                        'pid' => $pid,
                        'pkeys' => $pkeys_array[$i],
                        'pvalues' => $pvalues_array[$i],
                        'pcolors'=>$pcolors_array[$i],
                        'createAt' => NOW_TIME,
                        'updateAt' => NOW_TIME
                    );
                }
                D('pushed_param')->addAll($dataList);
                $this->success('新模板添加成功！', U('index'));
            } else {
                $this->error($Pushed->getError());
            }
        } else {
            $this->meta_title = '推送模板发布';
            $this->display();
        }
    }

    /**
     * 推送模板修改
     */
    public function edit($id = "",$title = "",$bin="",$templet="",$content = "",$jump_url = "") {
        if (IS_POST) {

            $newpkeys_array = I('newpkeys');
            $newpvalues_array = I('newpvalues');
            $newpcolors_array = I('newpcolors');

            //非空校验
            if (!$title) {
                $this->error("亲,模板标题不能为空哦!");
            }
            if (!$bin) {
                $this->error("亲,模板简码不能为空哦!");
            }
            if (!$templet) {
                $this->error("亲,公众号模板ID不能为空哦!");
            }
            if (!$content) {
                $this->error("亲,模板详情不能为空哦!");
            }

            if ($newpkeys_array) {
                for ($i = 0; $i < count($newpkeys_array); $i++) {

                    if ($newpkeys_array[$i] == ""  || $newpvalues_array[$i] == "" || $newpcolors_array[$i] == "") {
                        $this->error("亲,请确保每一行模板参数都不能有空值哦.");
                    }
                }
            }


            //数据操作
            $PushedData = array('title'=>$title,'bin' => $bin,'templet' => $templet,'content' => $content,'jump_url' => $jump_url,'updateAt' => NOW_TIME);
            $Pushed = D('Pushed');

            if ($Pushed->create($PushedData) && $Pushed->where(array('id' => $id))->save()) {
                if ($newpkeys_array) {
                    for ($i = 0; $i < count($newpkeys_array); $i++) {
                        $dataList[] = array(
                            'pid' => $id,
                            'pkeys' => $newpkeys_array[$i],
                            'pvalues' => $newpvalues_array[$i],
                            'pcolors'=>$newpcolors_array[$i],
                            'createAt' => NOW_TIME,
                            'updateAt' => NOW_TIME
                        );
                    }
                    D('pushed_param')->addAll($dataList);
                }
                $this->success('模板编辑成功！', U('index'));
            } else {
                $this->error($Pushed->getError());
            }
        } else {
            $data = M('Pushed')->where(array('id' => $id))->find();
            $paramlist = M('pushed_param')->where(array('pid' => $id, 'status' => 1))->select();
            $data['paramlist'] = $paramlist;
            $this->data = $data;
            $this->meta_title = '推送模板修改';
            $this->display();
        }
    }


    //删除模板
    public function del($id=""){
        IF ($id == "") {
            $this->error("模板刪除失败!");
        }
        $Data = array('status' => -1,'delflag'=>1,'updateAt'=>NOW_TIME);
        $Pushed = D('Pushed');
        if ($Pushed->where(array('id' => $id))->save($Data)) {

            $this->success("模板刪除成功!");
        } else {
            $this->error("模板刪除失败！");
        }
    }

    /**
     * 推送模板测试
     */
    public function test($id = "",$bin = "") {
        if (IS_POST) {

            $PushedData = array('title'=>$title,'bin' => $bin,'param1' => $param1,'param2' => $param2,'param3' => $param3,'param4' => $param4,'content' => $content,'updateAt' => NOW_TIME);
            $Pushed = D('Pushed');

            if ($Pushed->create($PushedData) && $Pushed->where(array('id' => $id))->save()) {
                $this->success('模板编辑成功！', U('index'));
            } else {
                $this->error($Pushed->getError());
            }
        } else {
            $Model = new Model();

            $sql = "select a.*,b.nickname from gr_ec.gr_push_user a,gr_api.gr_login_info b where a.uid = b.id and a.report_day = '2016-05-28'";
            $list = $Model -> query($sql);

            $this->_list = $list;
            $this->_id = $id;
            $this->_bin = $bin;
            $this->meta_title = '推送模板测试';
            $this->display();
        }
    }

    /**
     * 改变状态
     * @param type $id
     * @param type $flag
     */
    public function changeStatus($id="",$flag = ""){
        IF ($id == "" || $flag == "") {
            $this->error("操作失败！失败原因：参数异常!");
        }

        if($flag ==1){
            $f = 0;
        }else{
            $f = 1;
        }

        $Data = array('flag' => $f,'status' => $f,'updateAt'=>NOW_TIME);
        $Push = M('push_user');
        if ($Push->where(array('id' => $id))->save($Data)) {

            $this->success("操作成功!");
        } else {
            $this->error("操作失败！");
        }
    }

    /**
     * 推送模板管理
     * @author James
     * 2016-06-17
     */
    public function testin() {

        $id = I('id');
        $bin = I('bin');

        $uid = I('uid');

        if($uid){
            $Model = new Model();
            $sql = "select a.id,a.nickname,b.openid from gr_api.gr_login_info a,gr_api.gr_thirdparty b where a.id = b.uid and a.id = ".$uid;

            $list = $Model -> query($sql);

            $this->assign('_list', $list);
        }

        $this->assign('_id', $id);
        $this->assign('_bin', $bin);

        $this->meta_title = '添加测试用户';
        $this->display();
    }


    /**
     * 添加测试用户
     * @param type $id
     */
    public function addtestuser($id=""){
        IF ($id == "") {
            $this->error("操作失败！失败原因：参数异常!");
        }
        $Model = new \Think\Model();
        $sql = "insert into gr_push_user (report_day,bin,uid,openid,flag,delflag,createAt,updateAt)
                select '2016-05-28','ceshi',a.id,b.openid,0,0,UNIX_TIMESTAMP(),UNIX_TIMESTAMP()
                from gr_api.gr_login_info a,gr_api.gr_thirdparty b 
                where a.id = b.uid 
                and a.id = ".$id;
        $Model->execute($sql);

        $this->success("添加测试用户成功!");

    }

    /**
     * 推送转化
     */
    public function conversion($id = "") {

        $Model = new Model();

        $Pushed = M('Pushed')->where(array('id' => $id))->find();


        //模板标题:
        $title = $Pushed['title'];
        $bin = $Pushed['bin'];
        $updateAt = $Pushed['updateAt'];

        $format = 'Y-m-d';
        if(strlen($updateAt)>10){
            $sjc = $updateAt / 1000;
        }else{
            $sjc = $updateAt;
        }

        $report_day = date($format, intval($sjc));

        $sql = "select count(1) zyhs
            from gr_push_user_all a 
            where bin = '".$bin."'";
        $list = $Model -> query($sql);

        if($list[0]['zyhs'] == 0){
            $table = "gr_push_user";
        }else{
            $table = "gr_push_user_all";
        }

        $pushsql = "select count(1) zyhs,
            count(case when status = 1 then 1 end) cgyhs,
            count(case when status = -1 then 1 end) sbyhs
            from ".$table." a 
            where a.report_day = '".$report_day."' and bin = '".$bin."'";
        $pushlist = $Model -> query($pushsql);

        $zyhs = $pushlist[0]['zyhs'];
        $cgyhs = $pushlist[0]['cgyhs'];
        $sbyhs = $pushlist[0]['sbyhs'];

        $xdssql = "select count(1) xds
        from gr_final_order a,gr_final_order_group b 
        where a.groupNo = b.groupNo 
        and a.status >= 2000 
        and b.payTime >= ".$updateAt."
        and exists (select 1 from ".$table." c where b.uid = c.uid and c.status = 1 and c.report_day = '".$report_day."' and c.bin = '".$bin."' and b.payTime > c.updateAt)";
        $xdslist = $Model -> query($xdssql);

        $xds = $xdslist[0]['xds'];

        $this->_title = $title;     //模板标题
        $this->_zyhs = $zyhs;       //总推用户
        $this->_cgyhs = $cgyhs;     //已推成功数
        $this->_sbyhs = $sbyhs;     //已推失败数
        $this->_xds = $xds;         //下单数

        $this->meta_title = '推送转化';
        $this->display();

    }

    /**
     * 删除模板参数
     * @param type $id
     */
    public function paramdelajax($id = "") {

        IF ($id == "") {
            $this->error("模板参数刪除失败!");
        }

        $data = array('status' => -1,'delflag'=>1,'updateAt'=>NOW_TIME);
        $Pushedparam = D('pushed_param');
        if ($Pushedparam->where(array('id' => $id))->save($data)) {
            $this->success("模板参数刪除成功!");
        } else {
            $this->error("模板参数刪除失败！");
        }
    }
}
